// DocumentStorageService.java
package com.mobile.service.impl;

import com.mobile.service.entity.BusinessDocument;
import com.mobile.service.mapper.BusinessDocumentMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.util.UUID;

@Service
public class DocumentStorageService {
    
    @Resource
    private BusinessDocumentMapper businessDocumentMapper;

    // 文书存储基础路径 //todo 上线前修改文档路径
    private static final String DOCUMENT_BASE_PATH = "/documents/business/";
    
    /**
     * 保存文书到服务器
     * @param workOrderId 工单ID
     * @param businessType 业务类型
     * @param result 处理结果
     * @param fileContent 文件内容
     * @param fileName 文件名
     * @param documentType 文书类型
     * @return 保存的文书信息
     */
    public BusinessDocument saveDocument(Integer workOrderId, String businessType, String result, 
                                       byte[] fileContent, String fileName, String documentType) throws Exception {
        // 创建文件存储目录
        String fullPath = System.getProperty("user.dir") + DOCUMENT_BASE_PATH;
        File directory = new File(fullPath);
        if (!directory.exists()) {
            directory.mkdirs();
        }
        
        // 生成唯一文件名
        String uniqueFileName = UUID.randomUUID().toString() + "_" + fileName;
        String filePath = fullPath + uniqueFileName;
        
        // 保存文件到服务器
        try (FileOutputStream fos = new FileOutputStream(filePath)) {
            fos.write(fileContent);
        }
        
        // 保存文书信息到数据库
        BusinessDocument document = new BusinessDocument();
        document.workOrderId(workOrderId)
                .businessType(businessType)
                .result(result)
                .documentType(documentType)
                .fileName(fileName)
                .filePath(DOCUMENT_BASE_PATH + uniqueFileName)
                .createUser("system")
                .updateUser("system");

        // 保存到数据库
        businessDocumentMapper.insertBusinessDocument(document);
        
        return document;
    }
}
